package com.fulihui.information.core.zbus;

import com.alibaba.fastjson.JSON;
import com.fulihui.information.common.config.AppConst;
import org.near.toolkit.common.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.zbus.broker.Broker;
import org.zbus.broker.ZbusBroker;
import org.zbus.mq.Producer;
import org.zbus.net.http.Message;

import javax.annotation.PostConstruct;

/**
 * @author leeson 2016年5月8日 下午12:37:57
 *
 */
@Component
public class ZbusProducerHandle {
    @Autowired
    private AppConst appConst;

    private Broker   broker;
    private Producer dataProcessProducer;

    @PostConstruct
    public void init() throws Exception {
        broker = new ZbusBroker(appConst.getZbusUrl());
        dataProcessProducer = new Producer(broker, Const.QUEUE_NAME);
        dataProcessProducer.createMQ();
    }

    /**
     * 发送消息到消息队列
     * @param messageJson
     * @return
     */
    public boolean commitToMQ(String messageJson) {
        Message msg = new Message(messageJson);

        try {
            dataProcessProducer.sendSync(msg);
            Log.info("S->Q: " + JSON.parseObject(messageJson).getString("trackNo"));
            return true;
        } catch (Exception e) {
            Log.error(e.getMessage(), e);
            return false;
        }
    }
}